<template>
  <div>
    <div class="flex-center mb10px">
      <ElButton type="primary" link @click="selectAll">全选</ElButton>
      <ElButton type="success" link @click="selectDefault">默认</ElButton>
      <ElButton link @click="clear">清空</ElButton>
    </div>
    <el-tree ref="treeRef" :data="data"
      node-key="value"
      show-checkbox
      default-expand-all
      :default-checked-keys="defaultCheckedKeys"
      check-strictly
      @check-change="onCheckChange"
    />
  </div>
</template>
<script setup lang="ts">
  import { ElButton, ElTree, TreeInstance } from 'element-plus'
  import { computed, ref, watch } from 'vue'

  const props = defineProps<{modelValue?: string[]}>()
  const emits = defineEmits(['update:modelValue'])

  const defaultCheckedKeys = computed(() => props.modelValue || [])

  const treeRef = ref<TreeInstance>()
  const value = ref([])
  watch(() => value.value, () => console.log('value', value.value), { deep: true })
  const data = [
    {
      value: 'action',
      label: '功能',
      children: [
        {
          value: 'action-column',
          label: '列'
        },
        {
          value: 'action-stat',
          label: '统计'
        }
      ]
    },
    {
      value: 'home',
      label: '首页'
    },
    {
      value: 'seed',
      label: '模块',
      children: [
        {
          value: 'seed-action',
          label: '功能',
          children: [
            {
              value: 'seed-action-column',
              label: '列'
            },
            {
              value: 'seed-action-stat',
              label: '统计'
            }
          ]
        },
        {
          value: 'seed-column',
          label: '列'
        },
        {
          value: 'seed-has-one',
          label: '一对一'
        },
        {
          value: 'seed-belongs-to',
          label: '多对一'
        },
        {
          value: 'seed-has-many',
          label: '一对多'
        },
        {
          value: 'seed-habtm',
          label: '多对多'
        }
      ]
    }
  ]

  function onCheckChange() {
    emits('update:modelValue', treeRef.value.getCheckedKeys())
  }

  function selectAll() {
    treeRef.value.setCheckedKeys([
      'action',
      'action-column',
      'action-stat',
      'home',
      'seed',
      'seed-action',
      'seed-action-column',
      'seed-action-stat',
      'seed-column',
      'seed-has-one',
      'seed-belongs-to',
      'seed-has-many',
      'seed-habtm'
    ])
  }

  function selectDefault() {
    treeRef.value.setCheckedKeys(['action', 'home', 'seed', 'seed-action'])
  }

  function clear() {
    treeRef.value.setCheckedKeys([])
  }
</script>